package com.ktwlsoft.archivemanage.domain.business.businessService.businessInspect;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.ktwlsoft.archivemanage.domain.business.businessService.ArchiveUnitBusinessService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.ArchiveUnitRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.businessInspect.BusinessInspectRandomizingRepositoryService;
import com.ktwlsoft.archivemanage.domain.dao.entity.Account;
import com.ktwlsoft.archivemanage.domain.dao.entity.businessInspect.BusinessInspectRandomizing;
import com.ktwlsoft.archivemanage.domain.dao.repository.IAccountMapper;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.payload.businessInspect.BusinessInspectRandomizingSaveRequest;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import com.ktwlsoft.archivemanage.service.utils.SnowFlake;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 业务检查随机抽取服务
 *
 * @author Name on 2023/6/25 14:45
 * @version 1.0
 */
@Component
@RequiredArgsConstructor
public class BusinessInspectRandomizingService {

    private final BusinessInspectRandomizingRepositoryService service;

    private final ArchiveUnitRepositoryService unitRepositoryService;

    private final IAccountMapper accountMapper;

    /**
      * 保存或更新 on 2023/6/25 15:41
      *
      * @param request request
      * @return Result<?>
      */
    public Result<?> saveOrUpdate(List<BusinessInspectRandomizingSaveRequest> request){
        List<BusinessInspectRandomizing> list = BeanUtil.copyToList(request, BusinessInspectRandomizing.class);
        Account account = UserPrincipal.getCurrentUser();
        list.forEach(value ->{
            value.setId(SnowFlake.getNextId());
            if(account != null) {
                value.setCreator(account.getRealName());
                value.setCreatorId(account.getId());
                value.setCreatedAt(new Date());
                value.setUpdateKey(account.getRealName());
                value.setUpdateId(account.getId());
                value.setUpdateAt(new Date());
            }
        });
        try {
            service.lambdaUpdate().remove();
            service.saveBatch(list);
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(null, ResultType.SAVING_ERROR);
        }
        return Result.ok(null);
    }

    /**
     * 保存或更新 on 2023/6/25 15:41
     *
     * @return Result<?>
     */
    public Result<?> findList(String businessId,BusinessInspectRandomizing.businessType businessType){
        List<BusinessInspectRandomizing> list = service.lambdaQuery()
                .eq(StrUtil.isNotBlank(businessId),BusinessInspectRandomizing::getBusinessId,businessId)
                .eq(ObjectUtil.isNotEmpty(businessType),BusinessInspectRandomizing::getBusinessType,businessType)
                .list();
        return Result.ok(list);
    }

    /**
      * 随机抽取单位 on 2023/6/25 15:40
      *
      * @param num num
      * @return Result<?>
      */
    public Result<?> randomizingUnit(Integer num){
        List<BusinessInspectRandomizing> list = service.lambdaQuery()
                .eq(BusinessInspectRandomizing::getBusinessType,BusinessInspectRandomizing.businessType.UNIT)
                .list();
        List<JSONObject> ret = Lists.newArrayList();
        if(ObjectUtil.isNotEmpty(list)){
            Collections.shuffle(list);
            ret = list.stream().map(value ->{
                JSONObject object = new JSONObject();
                object.put("unitId",value.getBusinessId());
                object.put("unitName",value.getBusinessName());
                return object;
            }).collect(Collectors.toList()).subList(0,num);
        }else {
            JSONObject object = new JSONObject();
            object.put("enable", 1);
            List<JSONObject> unitJson = unitRepositoryService.findListAll(object);
            if(ObjectUtil.isNotEmpty(unitJson)){
                Collections.shuffle(unitJson);
                ret = unitJson.stream().map(value ->{
                    JSONObject unit = new JSONObject();
                    unit.put("unitId",Optional.ofNullable(value.get("id")).orElse(""));
                    unit.put("unitName",Optional.ofNullable(value.get("unitName")).orElse(""));
                    return unit;
                }).collect(Collectors.toList()).subList(0,num);
            }
        }
        return Result.ok(ret);
    }

    /**
     * 随机抽取人员 on 2023/6/25 15:40
     *
     * @param num num
     * @return Result<?>
     */
    public Result<?> randomizingPersonnel(Integer num){
        List<BusinessInspectRandomizing> list = service.lambdaQuery()
                .eq(BusinessInspectRandomizing::getBusinessType,BusinessInspectRandomizing.businessType.PERSONNEL)
                .list();
        List<JSONObject> ret = Lists.newArrayList();
        if(ObjectUtil.isNotEmpty(list)){
            Collections.shuffle(list);
            ret = list.stream().map(value ->{
                JSONObject object = new JSONObject();
                object.put("userId",value.getBusinessId());
                object.put("userName",value.getBusinessName());
                return object;
            }).collect(Collectors.toList()).subList(0,num);
        }else {
            List<Account> accounts = accountMapper.findListNotUnit(null);
            if(ObjectUtil.isNotEmpty(accounts)){
                Collections.shuffle(accounts);
                ret = accounts.stream().map(value ->{
                    JSONObject unit = new JSONObject();
                    unit.put("userId",value.getId());
                    unit.put("userName",value.getUserName());
                    return unit;
                }).collect(Collectors.toList()).subList(0,num);
            }
        }
        return Result.ok(ret);
    }
}